/*
 * @lc app=leetcode.cn id=290 lang=cpp
 * @lcpr version=30204
 *
 * [290] 单词规律
 */


// @lcpr-template-start
using namespace std;
#include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// @lcpr-template-end
// @lc code=start
class Solution {
public:
    bool wordPattern(string pattern, string s) {
        vector<string> strs;
        int start = 0;
        int pos = 0;
        while(pos != string::npos) {
            pos = s.find_first_of(' ', start);
            strs.emplace_back(s.substr(start, pos - start));
            start = pos + 1;
        }
        if (pattern.size() != strs.size()) {
            return false;
        }
        // 建立双向映射：模式字符->单词  和  单词->模式字符
        unordered_map<char, string> charToStr;
        unordered_map<string, char> strToChar;
        
        for (int i = 0; i < pattern.size(); ++i) {
            char c = pattern[i];
            string word = strs[i];
            // 检查字符到单词的映射
            if (charToStr.count(c)) {
                if (charToStr[c] != word) {
                    return false;
                }
            } 
            else {
                charToStr[c] = word;
            }
            // 检查单词到字符的映射（确保一一对应）
            if (strToChar.count(word)) {
                if (strToChar[word] != c) {
                    return false;
                }
            } 
            else {
                strToChar[word] = c;
            }
        }
        return true;
    }
};
// @lc code=end



/*
// @lcpr case=start
// "abba"\n"dog cat cat dog"\n
// @lcpr case=end

// @lcpr case=start
// "abba"\n"dog cat cat fish"\n
// @lcpr case=end

// @lcpr case=start
// "aaaa"\n"dog cat cat dog"\n
// @lcpr case=end

 */

